<template>
  <div class="kawaii-favorites">
    <div class="kawaii-favorites-container">
      <!-- 左侧导航 -->
      <div class="kawaii-favorites-sidebar">
        <!-- 我创建的收藏夹 -->
        <div class="kawaii-sidebar-section">
          <div class="kawaii-section-header" @click="toggleMyCreated">
            <i class="el-icon-folder"></i>
            <span>我创建的收藏夹</span>
            <i
              :class="[
                'el-icon-arrow-down',
                myCreatedExpanded ? 'expanded' : '',
              ]"
            ></i>
          </div>

          <div v-show="myCreatedExpanded" class="kawaii-section-content">
            <div
              v-for="folder in myFolders"
              :key="folder.id"
              :class="[
                'kawaii-sidebar-item',
                selectedFolder?.id === folder.id ? 'active' : '',
              ]"
              @click="selectFolder(folder)"
            >
              <i class="el-icon-folder"></i>
              <span class="kawaii-item-title">{{ folder.title }}</span>
              <span class="kawaii-item-count">{{ folder.count }}</span>
            </div>
            <div v-if="myFolders.length === 0" class="kawaii-empty-section">
              <p>暂无创建的收藏夹 (｡•́︿•̀｡)</p>
            </div>

            <!-- 添加创建收藏夹按钮 -->
            <div class="kawaii-create-folder" @click.stop="createFolder">
              <i class="el-icon-plus"></i>
              <span>新建收藏夹</span>
            </div>
          </div>
        </div>

        <!-- 我追的收藏夹 -->
        <div class="kawaii-sidebar-section">
          <div class="kawaii-section-header" @click="toggleFollowed">
            <i class="el-icon-star-on"></i>
            <span>我追的收藏夹</span>
            <i
              :class="[
                'el-icon-arrow-down',
                followedExpanded ? 'expanded' : '',
              ]"
            ></i>
          </div>

          <div v-show="followedExpanded" class="kawaii-section-content">
            <div
              v-for="folder in followedFolders"
              :key="folder.id"
              :class="[
                'kawaii-sidebar-item',
                selectedFolder?.id === folder.id ? 'active' : '',
              ]"
              @click="selectFolder(folder)"
            >
              <i class="el-icon-folder"></i>
              <span class="kawaii-item-title">{{ folder.title }}</span>
              <span class="kawaii-item-count">{{ folder.count }}</span>
            </div>

            <div
              v-if="followedFolders.length === 0"
              class="kawaii-empty-section"
            >
              <p>暂无追踪的收藏夹 (´･ω･`)</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区 -->
      <div class="kawaii-favorites-content">
        <!-- 加载状态 -->
        <div v-if="loading" class="kawaii-loading-container">
          <div class="kawaii-loading">
            <div class="kawaii-loading-circle"></div>
            <div class="kawaii-loading-text">加载中...</div>
          </div>
        </div>

        <!-- 内容区域 -->
        <template v-else>
          <!-- 收藏夹标题和信息 -->
          <div class="kawaii-folder-header" v-if="selectedFolder">
            <div class="kawaii-folder-info">
              <h2 class="kawaii-folder-title">{{ selectedFolder.title }}</h2>
              <div class="kawaii-folder-meta">
                <span class="kawaii-folder-privacy">
                  <i
                    :class="
                      selectedFolder.isPrivate ? 'el-icon-lock' : 'el-icon-view'
                    "
                  ></i>
                  {{ selectedFolder.isPrivate ? '私密' : '公开' }}
                </span>
                <span class="kawaii-folder-count">
                  {{ selectedFolder.count }}个视频
                </span>
                <span class="kawaii-folder-time">
                  更新于: {{ selectedFolder.updateTime }}
                </span>
              </div>
              <p
                v-if="selectedFolder.description"
                class="kawaii-folder-description"
              >
                {{ selectedFolder.description }}
              </p>
            </div>

            <div class="kawaii-folder-actions" v-if="isOwnSpace">
              <el-button
                v-if="selectedFolder.id !== 0"
                size="small"
                @click="editFolder(selectedFolder.id)"
                icon="el-icon-edit"
                class="kawaii-edit-btn"
              >
                编辑
              </el-button>
            </div>
          </div>

          <!-- 排序和筛选 -->
          <div class="kawaii-video-filter">
            <div class="kawaii-filter-left">
              <span class="kawaii-filter-label">排序方式</span>
              <div class="kawaii-sort-options">
                <div
                  class="kawaii-sort-btn"
                  :class="{ active: sortType === 'newest' }"
                  @click="sortType = 'newest'"
                >
                  <i class="el-icon-time"></i>
                  <span>最新发布</span>
                </div>
                <div
                  class="kawaii-sort-btn"
                  :class="{ active: sortType === 'popular' }"
                  @click="sortType = 'popular'"
                >
                  <i class="el-icon-video-play"></i>
                  <span>最多播放</span>
                </div>
              </div>
            </div>

            <div class="kawaii-filter-right">
              <div class="kawaii-search-box">
                <input
                  type="text"
                  v-model="searchKeyword"
                  @input="searchVideos"
                  placeholder="搜索喜欢的视频吧~"
                  class="kawaii-search-input"
                />
                <i class="el-icon-search kawaii-search-icon"></i>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="videos.length === 0" class="kawaii-empty-container">
            <img
              src="@/assets/icons/empty-box.svg"
              alt="暂无收藏内容"
              class="kawaii-empty-icon"
            />
            <p class="kawaii-empty-text">暂无收藏内容 (´｡• ᵕ •｡`)</p>
            <p v-if="isOwnSpace" class="kawaii-empty-hint">
              开始收藏你喜欢的视频吧 ⋆˚✿˖°
            </p>
          </div>

          <!-- 使用VideoList组件替代原有视频列表 -->
          <VideoList
            v-else
            :videos="mappedVideos"
            :loading="videoLoading"
            :no-more="videoNoMore"
            :highlight-keyword="searchKeyword"
            @load-more="handleVideoLoadMore"
            class="custom-video-list"
          />

          <!-- 分页 -->
          <div class="kawaii-pagination" v-if="filteredVideos.length > 0">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalVideos"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
            />
          </div>
        </template>
      </div>
    </div>

    <!-- 编辑收藏夹对话框 -->
    <el-dialog
      v-model="folderDialogVisible"
      :title="isEditingFolder ? '编辑收藏夹' : '新建收藏夹'"
      width="500px"
      class="kawaii-dialog"
    >
      <div class="kawaii-folder-form">
        <!-- 表单内容 -->
        <el-form :model="folderForm" label-width="80px">
          <el-form-item label="名称" required>
            <el-input
              v-model="folderForm.title"
              placeholder="快来给你的收藏夹命名吧"
              maxlength="20"
              show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="公开">
            <el-switch
              v-model="folderIsPublic"
              active-color="#fe4ea4"
            ></el-switch>
          </el-form-item>

          <el-form-item label="简介">
            <el-input
              type="textarea"
              v-model="folderForm.description"
              placeholder="可以简单描述下你的收藏夹"
              :rows="4"
              maxlength="200"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="kawaii-dialog-footer">
          <el-button
            class="kawaii-cancel-btn"
            @click="folderDialogVisible = false"
          >
            取消
          </el-button>
          <el-button
            class="kawaii-create-btn"
            type="primary"
            @click="saveFolder"
          >
            {{ isEditingFolder ? '保存修改' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 移动视频对话框 -->
    <el-dialog
      v-model="moveDialogVisible"
      title="移动到收藏夹"
      width="400px"
      class="kawaii-dialog"
    >
      <div class="folder-select-list">
        <div
          v-for="folder in myFolders.filter((f) => f.id !== selectedFolder?.id)"
          :key="folder.id"
          class="folder-select-item"
          @click="moveToFolder(folder)"
        >
          <i class="el-icon-folder"></i>
          <span>{{ folder.title }}</span>
        </div>
      </div>
      <template #footer>
        <span class="kawaii-dialog-footer">
          <el-button @click="moveDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认移除"
      width="30%"
      class="kawaii-dialog"
    >
      <span>确定要从当前收藏夹移除此视频吗？</span>
      <template #footer>
        <span class="kawaii-dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmRemoveVideo">
            确认移除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import useUserStore from '@/store/modules/user'
import VideoList from '@/views/front/videoList/VideoList.vue'

// 定义收藏夹和视频类型，避免类型错误
interface Folder {
  id: number
  title: string
  count: number
  isPrivate: boolean
  updateTime: string
  description: string
  owner: {
    id: string | number
    name: string
  }
}

interface Video {
  id: number
  title: string
  cover: string
  duration: number
  playCount: number
  danmuCount: number
  commentCount: number
  favoriteCount: number
  uploaderName: string
  uploaderAvatar: string
  addTime: string
  addTimeRaw: string
}

interface FolderForm {
  id: number | null
  title: string
  description: string
  isPrivate: boolean
}

const props = defineProps({
  userId: {
    type: [String, Number],
    required: true,
  },
})

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 是否是用户自己的空间
const isOwnSpace = computed(() => {
  return props.userId === userStore.id
})

// 状态变量
const loading = ref(true)
const myCreatedExpanded = ref(true)
const followedExpanded = ref(true)
const folderDialogVisible = ref(false)
const moveDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const isEditingFolder = ref(false)
const selectedFolder = ref<Folder | null>(null)
const currentVideoToMove = ref<Video | null>(null)

// 收藏夹列表
const myFolders = ref<Folder[]>([])
const followedFolders = ref<Folder[]>([])

// 视频列表相关
const videos = ref<Video[]>([])
const totalVideos = ref(0)
const pageSize = ref(20)
const currentPage = ref(1)
const sortType = ref('newest')
const searchKeyword = ref('')
const selectedFolderId = ref<number | null>(null)

// 收藏夹表单
const folderForm = ref<FolderForm>({
  id: null,
  title: '',
  description: '',
  isPrivate: false,
})

// 处理开关组件双向绑定
const folderIsPublic = computed({
  get: () => !folderForm.value.isPrivate,
  set: (value) => {
    folderForm.value.isPrivate = !value
  },
})

// 根据搜索和排序过滤视频
const filteredVideos = computed<Video[]>(() => {
  let result = [...videos.value]

  // 搜索过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(
      (video) =>
        video.title.toLowerCase().includes(keyword) ||
        video.uploaderName.toLowerCase().includes(keyword),
    )
  }

  // 排序
  if (sortType.value === 'newest') {
    result.sort(
      (a, b) =>
        new Date(b.addTimeRaw).getTime() - new Date(a.addTimeRaw).getTime(),
    )
  } else if (sortType.value === 'popular') {
    result.sort((a, b) => b.playCount - a.playCount)
  }

  return result
})

// 格式化数字
const formatCount = (count: number): string => {
  if (!count && count !== 0) return '0'
  if (count === 0) return '0'

  if (count < 10000) {
    return count.toString()
  } else if (count < 100000000) {
    return (count / 10000).toFixed(1) + '万'
  } else {
    return (count / 100000000).toFixed(1) + '亿'
  }
}

// 格式化时长
const formatDuration = (seconds: number): string => {
  if (!seconds) return '00:00'

  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 格式化日期
const formatDate = (date: Date): string => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  // 小于一天，显示x小时前
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000)
    return hours > 0 ? `${hours}小时前` : '刚刚'
  }

  // 小于一个月，显示x天前
  if (diff < 2592000000) {
    return `${Math.floor(diff / 86400000)}天前`
  }

  // 否则显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 切换"我创建的收藏夹"的展开状态
const toggleMyCreated = () => {
  myCreatedExpanded.value = !myCreatedExpanded.value
}

// 切换"我追的收藏夹"的展开状态
const toggleFollowed = () => {
  followedExpanded.value = !followedExpanded.value
}

// 选择收藏夹
const selectFolder = (folder: Folder) => {
  selectedFolder.value = folder
  fetchVideos()
}

// 获取收藏夹列表
const fetchFolders = async () => {
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500))

    // 创建默认收藏夹
    const defaultFolder: Folder = {
      id: 0,
      title: '默认收藏夹',
      count: Math.floor(Math.random() * 30) + 10,
      isPrivate: false,
      updateTime: formatDate(new Date()),
      description: '系统默认创建的收藏夹，用于存放收藏的视频',
      owner: {
        id: userStore.id,
        name: userStore.nickname || '用户',
      },
    }

    // 创建其他收藏夹
    const mockFolders: Folder[] = Array.from({ length: 5 }, (_, i) => {
      const date = new Date()
      date.setDate(date.getDate() - Math.floor(Math.random() * 30))

      return {
        id: i + 1,
        title: getFolderName(i),
        count: Math.floor(Math.random() * 20) + 5,
        isPrivate: i % 3 === 0,
        updateTime: formatDate(date),
        description:
          i % 2 === 0
            ? `这是收藏夹${i + 1}的描述信息，可以添加自己喜欢的视频。`
            : '',
        owner: {
          id: userStore.id,
          name: userStore.nickname || '用户',
        },
      }
    })

    // 创建他人收藏夹（我追的收藏夹）
    const mockFollowedFolders: Folder[] = Array.from({ length: 3 }, (_, i) => {
      const date = new Date()
      date.setDate(date.getDate() - Math.floor(Math.random() * 20))

      return {
        id: 100 + i,
        title: getFollowedFolderName(i),
        count: Math.floor(Math.random() * 50) + 20,
        isPrivate: false,
        updateTime: formatDate(date),
        description: `UP主分享的优质内容集合，持续更新中...`,
        owner: {
          id: 1000 + i,
          name: `UP主${i + 1}`,
        },
      }
    })

    myFolders.value = [defaultFolder, ...mockFolders]
    followedFolders.value = mockFollowedFolders

    // 默认选中第一个收藏夹
    selectedFolder.value = myFolders.value[0]

    // 获取当前选中收藏夹的视频列表
    fetchVideos()
  } catch (error) {
    console.error('获取收藏夹列表失败:', error)
    ElMessage.error('获取收藏夹列表失败')
  } finally {
    loading.value = false
  }
}

// 获取收藏夹中的视频
const fetchVideos = async () => {
  if (!selectedFolder.value) return

  loading.value = true

  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 800))

    // 生成模拟视频数据
    const count = Math.min(selectedFolder.value.count, 50)
    const mockVideos: Video[] = Array.from({ length: count }, (_, i) => {
      const addDate = new Date()
      addDate.setDate(addDate.getDate() - Math.floor(Math.random() * 30))

      return {
        id: 1000 + i,
        title: getVideoTitle(i),
        cover: `/src/assets/banner/${(i % 3) + 1}.jpg`,
        duration: Math.floor(Math.random() * 900) + 60, // 1-15分钟
        playCount: Math.floor(Math.random() * 500000) + 1000,
        danmuCount: Math.floor(Math.random() * 10000) + 100,
        commentCount: Math.floor(Math.random() * 2000) + 50,
        favoriteCount: Math.floor(Math.random() * 1000) + 100,
        uploaderName: `UP主${Math.floor(Math.random() * 10) + 1}`,
        uploaderAvatar:
          'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        addTime: formatDate(addDate),
        addTimeRaw: addDate.toISOString(),
      }
    })

    videos.value = mockVideos
    totalVideos.value = selectedFolder.value.count
  } catch (error) {
    console.error('获取视频列表失败:', error)
    ElMessage.error('获取视频列表失败')
  } finally {
    loading.value = false
  }
}

// 获取收藏夹名称
const getFolderName = (index: number): string => {
  const names = [
    '精选视频',
    '学习资料',
    '动漫收藏',
    '音乐现场',
    '经典电影',
    '游戏攻略',
    '编程教程',
    '美食推荐',
  ]

  return names[index % names.length]
}

// 获取关注的收藏夹名称
const getFollowedFolderName = (index: number): string => {
  const names = ['精彩视频合集', '官方精选', '每周必看', '高分推荐', '新人必看']

  return names[index % names.length]
}

// 获取视频标题
const getVideoTitle = (index: number): string => {
  const titles = [
    '【Java教程】零基础入门Java编程，一周入门到精通',
    '深入浅出Vue3.0核心概念解析与实战应用',
    'Python数据分析从入门到进阶【完整版】',
    '5分钟带你了解Spring Boot核心功能与开发流程',
    '前端面试常见问题解析与答题技巧分享',
    '计算机网络基础知识——TCP/IP协议详解',
    '数据结构与算法分析——力扣高频题目讲解',
    '零基础学习Web开发全栈技术（HTML/CSS/JS）',
    '【设计模式】23种设计模式详解与实战应用',
    '微服务架构设计与实现——Docker+K8s+SpringCloud',
  ]

  return titles[index % titles.length]
}

// 获取动漫标题
const getAnimeTitle = (index: number): string => {
  const animeTitles = [
    '【解析】物语系列观看顺序详解与剧情梳理',
    '【AMV】EVA终章-破与Q-超燃混剪「新世纪福音战士」',
    '【熟肉】JOJO第六部Stone Ocean最新PV',
    '【分析】鬼灭之刃为何能成为现象级动画',
    '【考据】动画中10大被误用的日本文化元素',
    '【剧场版】魔法少女小圆：叛逆的物语超清修复版',
    '【自制】国漫崛起之路：从星游记到斗罗大陆',
    '【MAD】哔哩哔哩热门动画角色人气大盘点2023',
    '【催泪】那些让人落泪的动画场景合集',
    '【解说】宫崎骏的世界观与创作理念全解析',
    '【合集】浅谈京都动画的视觉美学及风格演变',
    '【访谈】进击的巨人作者谏山创完结感言全程',
    '【混剪】动漫中的那些震撼战斗场面TOP20',
    '【科普】日本动画制作流程全解析',
    '【吐槽】为什么异世界穿越题材总是这么多',
    '【盘点】2023年不容错过的十大新番动画',
    '【评测】那些被低估的优秀动画作品',
    '【解密】声优业界不为人知的幕后故事',
    '【技术】动画特效制作的进化史',
    '【怀旧】八九十年代经典动画的时代印记',
  ]

  return animeTitles[index % animeTitles.length]
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchVideos()
}

// 搜索视频
const searchVideos = () => {
  // 实际项目中可能需要调用API
  // 这里使用computed属性filteredVideos已经实现了本地搜索
}

// 查看视频
const viewVideo = (video: Video) => {
  router.push(`/front/videoDetail/${video.id}`)
}

// 创建收藏夹
const createFolder = () => {
  isEditingFolder.value = false
  folderForm.value = {
    id: null,
    title: '',
    description: '',
    isPrivate: false,
  }
  folderDialogVisible.value = true
}

// 编辑收藏夹
const editFolder = (id: number) => {
  if (id === 0) {
    ElMessage.warning('默认收藏夹不能编辑')
    return
  }

  isEditingFolder.value = true
  const folder = myFolders.value.find((f) => f.id === id)

  if (folder) {
    folderForm.value = {
      id: folder.id,
      title: folder.title,
      description: folder.description || '',
      isPrivate: folder.isPrivate,
    }
    folderDialogVisible.value = true
  }
}

// 保存收藏夹
const saveFolder = async () => {
  if (!folderForm.value.title.trim()) {
    ElMessage.warning('请输入收藏夹名称')
    return
  }

  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500))

    if (isEditingFolder.value) {
      // 更新收藏夹
      const index = myFolders.value.findIndex(
        (f) => f.id === folderForm.value.id,
      )
      if (index !== -1) {
        myFolders.value[index] = {
          ...myFolders.value[index],
          title: folderForm.value.title,
          description: folderForm.value.description,
          isPrivate: folderForm.value.isPrivate,
          updateTime: '刚刚',
        }

        // 如果更新的是当前选中的收藏夹，同步更新
        if (selectedFolder.value?.id === folderForm.value.id) {
          selectedFolder.value = {
            ...selectedFolder.value,
            title: folderForm.value.title,
            description: folderForm.value.description,
            isPrivate: folderForm.value.isPrivate,
            updateTime: '刚刚',
          }
        }
      }

      ElMessage.success('收藏夹更新成功')
    } else {
      // 创建新收藏夹
      const newId = Date.now()
      const newFolder: Folder = {
        id: newId,
        title: folderForm.value.title,
        description: folderForm.value.description,
        count: 0,
        isPrivate: folderForm.value.isPrivate,
        updateTime: '刚刚',
        owner: {
          id: userStore.id,
          name: userStore.nickname || '用户',
        },
      }

      myFolders.value.push(newFolder)
      ElMessage.success('收藏夹创建成功')
    }

    folderDialogVisible.value = false
  } catch (error) {
    console.error('保存收藏夹失败:', error)
    ElMessage.error('保存收藏夹失败')
  }
}

// 处理视频操作
const handleVideoCommand = (command: string, video: Video) => {
  if (command === 'moveToFolder') {
    currentVideoToMove.value = video
    moveDialogVisible.value = true
  } else if (command === 'remove') {
    ElMessageBox.confirm('确定要从收藏夹中移除此视频吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        // 移除视频
        videos.value = videos.value.filter((v) => v.id !== video.id)
        if (selectedFolder.value) {
          selectedFolder.value.count--
        }
        totalVideos.value--

        ElMessage.success('视频已从收藏夹中移除')
      })
      .catch(() => {})
  }
}

// 移动视频到其他收藏夹
const moveToFolder = (targetFolder: Folder) => {
  if (!currentVideoToMove.value || !selectedFolder.value) return

  // 模拟移动视频
  const videoTitle = currentVideoToMove.value.title
  const truncatedTitle =
    videoTitle.length > 15 ? `${videoTitle.substring(0, 15)}...` : videoTitle

  // 增加目标收藏夹数量
  targetFolder.count++

  // 减少当前收藏夹数量
  selectedFolder.value.count--

  // 从当前视频列表中移除
  videos.value = videos.value.filter(
    (v) => v.id !== currentVideoToMove.value!.id,
  )
  totalVideos.value--

  ElMessage.success(
    `已将视频"${truncatedTitle}"移动到收藏夹"${targetFolder.title}"`,
  )
  moveDialogVisible.value = false
  currentVideoToMove.value = null
}

// 删除收藏夹对话框
const showDeleteDialog = (id: number) => {
  if (id === 0) {
    ElMessage.warning('默认收藏夹不能删除')
    return
  }

  selectedFolderId.value = id
  deleteDialogVisible.value = true
}

// 确认删除
const confirmRemoveVideo = async () => {
  if (!selectedFolderId.value) return

  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500))

    // 从列表中移除
    myFolders.value = myFolders.value.filter(
      (f) => f.id !== selectedFolderId.value,
    )

    // 如果删除的是当前选中的收藏夹，切换到默认收藏夹
    if (selectedFolder.value?.id === selectedFolderId.value) {
      selectedFolder.value = myFolders.value[0]
      fetchVideos()
    }

    // 关闭对话框
    deleteDialogVisible.value = false
    selectedFolderId.value = null

    ElMessage.success('视频已从收藏夹中移除')
  } catch (error) {
    console.error('删除视频失败:', error)
    ElMessage.error('删除视频失败')
  }
}

// 处理收藏夹命令
const handleFolderCommand = (command: { type: string; id: number }) => {
  if (command.type === 'edit') {
    editFolder(command.id)
  } else if (command.type === 'delete') {
    showDeleteDialog(command.id)
  }
}

// 视频相关状态
const videoLoading = ref(false)
const videoNoMore = ref(false)

// 将内部视频数据转换为VideoList组件所需格式
const mappedVideos = computed(() => {
  return filteredVideos.value.map((video, index) => {
    return {
      id: video.id,
      title: getAnimeTitle(index),
      thumbnail: `/src/assets/anime/images/banner${(index % 16) + 1}.png`,
      duration: video.duration,
      viewCount: video.playCount,
      danmuCount: video.danmuCount,
      author: video.uploaderName,
      createTime: video.addTime,
      tags: video.title.includes('动漫')
        ? ['动画', '热血', '国漫']
        : video.title.includes('MAD')
          ? ['MAD', 'AMV', '混剪']
          : ['二次元', '热门', '解说'],
    }
  })
})

// 处理VideoList组件的加载更多事件
const handleVideoLoadMore = () => {
  if (currentPage.value * pageSize.value < totalVideos.value) {
    currentPage.value++
    fetchVideos()
  } else {
    videoNoMore.value = true
  }
}

// 初始化
onMounted(() => {
  fetchFolders()
})
</script>

<style scoped lang="scss">
.kawaii-favorites {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.kawaii-favorites-container {
  display: flex;
  gap: 20px;

  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.kawaii-favorites-sidebar {
  width: 220px;
  flex-shrink: 0;

  @media (max-width: 768px) {
    width: 100%;
  }
}

.kawaii-sidebar-section {
  background: rgba(255, 255, 255, 0.7);
  border-radius: 16px;
  margin-bottom: 15px;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(255, 182, 193, 0.2);
  border: 2px solid rgba(255, 182, 193, 0.3);
  backdrop-filter: blur(5px);
}

.kawaii-section-header {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  background: linear-gradient(to right, #ffcbe3, #ffd6ff);
  color: #7c5479;
  font-weight: bold;
  cursor: pointer;

  i {
    margin-right: 8px;

    &.el-icon-arrow-down {
      margin-left: auto;
      margin-right: 0;
      transition: transform 0.3s;

      &.expanded {
        transform: rotate(180deg);
      }
    }
  }
}

.kawaii-section-content {
  padding: 8px 0;
  max-height: 300px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #ffcbe3;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.5);
  }
}

.kawaii-sidebar-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  color: #7c5479;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;

  &:hover {
    background-color: rgba(255, 200, 227, 0.2);
  }

  &.active {
    background-color: rgba(255, 200, 227, 0.3);
    font-weight: bold;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      width: 3px;
      background: linear-gradient(to bottom, #fe4ea4, #ff9fcf);
    }
  }

  i {
    margin-right: 8px;
    color: #fe4ea4;
  }
}

.kawaii-item-title {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.kawaii-item-count {
  padding: 2px 6px;
  background: rgba(255, 182, 193, 0.2);
  border-radius: 10px;
  font-size: 12px;
  margin-left: 5px;
}

.kawaii-empty-section {
  text-align: center;
  padding: 15px;
  color: #99809d;
  font-size: 14px;
}

.kawaii-favorites-content {
  flex: 1;
  min-width: 0;
}

.kawaii-loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.kawaii-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.kawaii-loading-circle {
  width: 50px;
  height: 50px;
  border: 4px solid #ffcbe3;
  border-top-color: #fe4ea4;
  border-radius: 50%;
  animation: spin 1s infinite linear;
}

.kawaii-loading-text {
  color: #7c5479;
  font-size: 16px;
  font-weight: bold;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.kawaii-folder-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 16px;
  padding: 15px 20px;
  box-shadow: 0 4px 10px rgba(255, 182, 193, 0.2);
  border: 2px solid rgba(255, 182, 193, 0.3);
}

.kawaii-folder-title {
  font-size: 20px;
  color: #7c5479;
  margin: 0 0 10px 0;
}

.kawaii-folder-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 10px;
  font-size: 13px;
  color: #99809d;

  i {
    margin-right: 5px;
  }
}

.kawaii-folder-description {
  margin: 0;
  font-size: 14px;
  color: #7c5479;
}

.kawaii-edit-btn {
  min-width: 100px;
  background: linear-gradient(to right, #fe4ea4, #ff99ac);
  border: none;
  border-radius: 20px;
  color: white;
  padding: 8px 15px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(254, 78, 164, 0.3);
    background: linear-gradient(to right, #fe4ea4, #ff7097);
  }
}

.kawaii-video-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: rgba(255, 242, 255, 0.7);
  border-radius: 16px;
  padding: 12px 20px;
  box-shadow: 0 4px 10px rgba(255, 182, 193, 0.2);
  border: 2px solid rgba(254, 78, 164, 0.2);
  backdrop-filter: blur(5px);
}

.kawaii-filter-label {
  margin-right: 15px;
  color: #fe4ea4;
  font-weight: bold;
  font-size: 15px;
}

.kawaii-filter-left {
  display: flex;
  align-items: center;
}

.kawaii-sort-options {
  display: flex;
  gap: 10px;
}

.kawaii-sort-btn {
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid #ffd6ff;
  border-radius: 20px;
  padding: 6px 15px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;

  i {
    color: #fe4ea4;
    margin-right: 5px;
    font-size: 16px;
  }

  span {
    color: #7c5479;
    font-size: 14px;
  }

  &:hover {
    background: rgba(255, 214, 255, 0.7);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(254, 78, 164, 0.2);
  }

  &.active {
    background: linear-gradient(to right, #ffb6c1, #ffd6ff);
    border-color: #fe4ea4;
    box-shadow: 0 4px 8px rgba(254, 78, 164, 0.3);

    span {
      color: #fe4ea4;
      font-weight: bold;
    }
  }
}

.kawaii-filter-right {
  width: 220px;

  @media (max-width: 768px) {
    width: 100%;
    margin-top: 10px;
  }
}

.kawaii-search-box {
  position: relative;
  width: 100%;
}

.kawaii-search-input {
  width: 100%;
  height: 36px;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid #ffd6ff;
  border-radius: 20px;
  padding: 0 15px 0 35px;
  color: #7c5479;
  font-size: 14px;
  transition: all 0.3s;
  outline: none;

  &::placeholder {
    color: #c9a0dc;
  }

  &:focus {
    border-color: #fe4ea4;
    box-shadow: 0 0 10px rgba(254, 78, 164, 0.2);
    background: rgba(255, 255, 255, 0.9);
  }
}

.kawaii-search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #fe4ea4;
  font-size: 16px;
}

.kawaii-empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 10px rgba(255, 182, 193, 0.2);
  border: 2px solid rgba(255, 182, 193, 0.3);
  backdrop-filter: blur(5px);
}

.kawaii-empty-icon {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
  animation: float 3s infinite ease-in-out;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-10px);
  }
}

.kawaii-empty-text {
  font-size: 18px;
  color: #7c5479;
  font-weight: bold;
  margin-bottom: 10px;
}

.kawaii-empty-hint {
  font-size: 14px;
  color: #99809d;
}

.kawaii-video-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.kawaii-video-item {
  transition: all 0.3s ease;
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  position: relative;

  &:hover {
    transform: translateY(-5px);
  }
}

.kawaii-video-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 6px 16px rgba(254, 78, 164, 0.2);
  }
}

.kawaii-video-cover {
  position: relative;
  overflow: hidden;
  padding-top: 56.25%;
  /* 16:9 Aspect Ratio */

  img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.kawaii-video-overlay {
  display: none;
}

.kawaii-video-play-btn {
  display: none;
}

.kawaii-video-stats {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 8px 10px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0));
  display: flex;
  align-items: center;
  z-index: 1;
}

.kawaii-stat-item {
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 12px;
  margin-right: 12px;

  i {
    margin-right: 4px;
    font-size: 14px;
  }
}

.kawaii-video-duration {
  position: absolute;
  right: 10px;
  bottom: 8px;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 12px;
  padding: 1px 6px;
  border-radius: 4px;
}

.kawaii-video-info {
  padding: 12px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.kawaii-video-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 40px;
  line-height: 1.4;
}

.kawaii-video-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.kawaii-uploader {
  display: flex;
  align-items: center;

  i {
    color: #fb7299;
    font-size: 14px;
    margin-right: 6px;
  }
}

.kawaii-uploader-name {
  font-size: 12px;
  color: #fb7299;
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.kawaii-publish-time {
  font-size: 12px;
  color: #999;
}

.kawaii-video-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.kawaii-tag {
  font-size: 12px;
  color: #fb7299;
  background: rgba(251, 114, 153, 0.1);
  border-radius: 4px;
  padding: 2px 6px;
}

.kawaii-video-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;

  i {
    color: #fe4ea4;
  }

  &:hover {
    background-color: #fff;
    transform: rotate(90deg);
  }
}

.kawaii-pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;

  :deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
    background-color: #fe4ea4;
  }

  :deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
    color: #fe4ea4;
  }

  :deep(.el-pagination.is-background .btn-prev:hover),
  :deep(.el-pagination.is-background .btn-next:hover) {
    color: #fe4ea4;
  }
}

.kawaii-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(to right, #fe4ea4, #ffd6ff);
    padding: 15px 20px;
    border-radius: 10px 10px 0 0;
    position: relative;
    width: 100%;
    box-sizing: border-box;
    margin: 0;
  }

  :deep(.el-dialog__title) {
    color: white;
    font-weight: bold;
    font-size: 18px;
    width: 100%;
    text-align: center;
  }

  :deep(.el-dialog__headerbtn) {
    position: absolute;
    top: 15px;
    right: 20px;

    .el-dialog__close {
      color: white;
      font-size: 20px;

      &:hover {
        transform: rotate(90deg);
        transition: transform 0.3s;
      }
    }
  }

  :deep(.el-dialog__body) {
    background-color: #fff;
    padding: 20px;
    color: #7c5479;
  }

  :deep(.el-dialog__footer) {
    background-color: #fff;
    padding: 10px 20px 20px;
    border-radius: 0 0 10px 10px;
  }

  :deep(.el-input__wrapper) {
    border-radius: 20px;
    box-shadow: 0 0 0 1px rgba(254, 78, 164, 0.2) inset;

    &:focus-within {
      box-shadow: 0 0 0 2px rgba(254, 78, 164, 0.4) inset;
    }
  }

  :deep(.el-textarea__wrapper) {
    border-radius: 12px;

    &:focus-within {
      box-shadow: 0 0 0 2px rgba(254, 78, 164, 0.4) inset;
    }
  }

  :deep(.el-form-item__label) {
    font-weight: 600;
    color: #7c5479;
  }

  :deep(.el-input__count) {
    background: transparent;
    color: #c9a0dc;
  }
}

.kawaii-dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;

  :deep(.el-button) {
    border-radius: 20px;
    padding: 10px 25px;
    font-size: 16px;
  }

  .kawaii-cancel-btn {
    border-color: #d3d7de;
    color: #606266;

    &:hover {
      color: #fe4ea4;
      border-color: #fe4ea4;
    }
  }

  .kawaii-create-btn {
    min-width: 100px;
    background: linear-gradient(to right, #fe4ea4, #ff99ac);
    border: none;
    border-radius: 20px;
    color: white;
    padding: 8px 20px;
    font-weight: 600;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(254, 78, 164, 0.3);
      background: linear-gradient(to right, #fe4ea4, #ff7097);
    }
  }
}

.kawaii-create-folder {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 15px;
  margin: 10px 15px;
  background: linear-gradient(to right, #ffcbe3, #ffd6ff);
  border-radius: 20px;
  color: #fe4ea4;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px dashed #fe4ea4;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(254, 78, 164, 0.3);
    background: linear-gradient(to right, #ffc0db, #ffc9f9);
  }

  i {
    margin-right: 6px;
    font-size: 16px;
  }

  span {
    font-weight: 600;
    font-size: 14px;
  }
}

.kawaii-folder-form {
  padding: 10px;
}

.kawaii-folder-cover {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.kawaii-cover-upload {
  width: 220px;
  height: 120px;
  background-color: #f5f5f5;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 2px dashed #dcdfe6;
  transition: all 0.3s;

  &:hover {
    border-color: #fe4ea4;
    background-color: rgba(254, 78, 164, 0.05);
  }

  i {
    font-size: 32px;
    color: #909399;
  }
}

/* 自定义VideoList组件样式 */
.custom-video-list {
  :deep(.videos-grid) {
    grid-template-columns: repeat(4, 1fr) !important;
    gap: 16px !important;

    @media (max-width: 1200px) {
      grid-template-columns: repeat(3, 1fr) !important;
    }

    @media (max-width: 992px) {
      grid-template-columns: repeat(2, 1fr) !important;
    }

    @media (max-width: 768px) {
      grid-template-columns: repeat(1, 1fr) !important;
    }
  }

  :deep(.video-container) {
    transition: all 0.3s ease;
    border: 2px solid rgba(254, 78, 164, 0.1);

    &:hover {
      border-color: rgba(254, 78, 164, 0.5);
    }

    .thumbnail-container {
      &::after {
        background: linear-gradient(
          45deg,
          rgba(254, 78, 164, 0.3),
          rgba(255, 214, 255, 0.2)
        ) !important;
      }
    }

    .video-title {
      font-size: 14px !important;
      font-weight: 600 !important;
    }

    .tag {
      border: 1px solid rgba(254, 78, 164, 0.3) !important;
    }
  }
}
</style>
